package com.whfc.cncit.helmet.server;

import com.whfc.cncit.entity.CncitUpMsg;
import com.whfc.cncit.helmet.processor.CncitUpMsgProcessor;
import com.whfc.cncit.helmet.processor.HelmetUpMsgProcessorFactory;
import com.whfc.common.enums.DeviceType;
import com.whfc.hdc.dto.AppDeviceDTO;
import com.whfc.hdc.service.AppDeviceService;
import com.whfc.iot.handler.DefaultServerHandler;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import com.whfc.iot.util.LoggingUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2018/11/29 10:41
 */
@ChannelHandler.Sharable
@Component
public class HelmetServerHandler extends DefaultServerHandler {

    private Logger logger = LoggerFactory.getLogger(HelmetServerHandler.class);

    @Autowired
    private HelmetUpMsgProcessorFactory processorFactory;

    @Autowired
    private SessionManager sessionManager;

    @DubboReference(interfaceClass = AppDeviceService.class, version = "1.0.0")
    private AppDeviceService deviceService;

    public HelmetServerHandler() {
        super();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("{}", LoggingUtil.format(ctx, "CHANNEL_READ", msg));
        try {
            CncitUpMsg reqMsg = (CncitUpMsg) msg;
            String deviceCode = reqMsg.getDeviceCode();
            Integer deviceType = DeviceType.helmet.getValue();
            AppDeviceDTO device = deviceService.getDeviceByCode(deviceCode);
            if (device == null || !deviceType.equals(device.getType())) {
                logger.warn("非法设备连接,deviceCode:{},deviceType:{}", deviceCode, deviceType);
                ctx.close();
                return;
            }
            Integer deviceId = device.getId();
            reqMsg.setDeviceId(deviceId);

            Session session = sessionManager.getSessionByDeviceId(deviceId);
            //构建session
            if (session == null) {
                session = sessionManager.createSession(deviceType, deviceId, ctx.channel());
            }
            //当前channel与session中的channel不一致
            if (!session.getChannel().equals(ctx.channel())) {
                session.getChannel().close().addListener(future -> {
                    logger.info("旧连接关闭,deviceId={},isDone={},isSuccess={}", deviceId, future.isDone(), future.isSuccess());
                });
                session = sessionManager.createSession(deviceType, deviceId, ctx.channel());
            }

            //处理消息
            CncitUpMsgProcessor processor = processorFactory.getMsgProcessor(reqMsg.getCmd());
            if (processor != null) {
                reqMsg.setExt1(device.getExt1());
                processor.processMsg(reqMsg);
            }
        } catch (Throwable ex) {
            logger.error("处理消息失败", ex);
        }
    }
}
